<template>
  <div class="page">
    <div class="page-header">
      <div class="page-title">
        <h2>👨‍🎓 学生信息管理</h2>
        <p class="page-subtitle">管理学生基本信息，包括学号、姓名、专业、宿舍分配等</p>
      </div>
      <div class="page-actions">
        <el-button size="large" @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button type="primary" size="large" @click="showAddModal = true; dialogVisible = true">
          <el-icon><Plus /></el-icon>
          新增学生
        </el-button>
      </div>
    </div>
    
    <el-card class="content-card" shadow="never">
      <template #header>
        <div class="search-section">
          <el-input
            v-model="searchQuery"
            placeholder="搜索姓名"
            class="search-box"
            size="large"
            clearable
            @keyup.enter="handleSearch"
            @clear="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <div class="filter-section">
             <el-select v-model="selectedProfession" placeholder="全部专业" size="large" clearable style="width: 160px">
               <el-option label="全部专业" value="" />
               <el-option 
                 v-for="profession in professions" 
                 :key="profession.id" 
                 :label="profession.name" 
                 :value="profession.id" 
               />
             </el-select>
            <el-select v-model="selectedStatus" placeholder="全部状态" size="large" clearable style="width: 140px">
              <el-option label="全部状态" value="" />
              <el-option label="正常" value="0" />
              <el-option label="禁用" value="1" />
            </el-select>
          </div>
          <el-button type="primary" size="large" @click="handleSearch" style="margin-left: 12px">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
      </template>
      
      <el-table
        :data="filteredStudents"
        stripe
        size="large"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="professionInfo.name" label="专业" width="120" />
        <el-table-column prop="grade" label="年级" width="100" />
        <el-table-column prop="sexText" label="性别" width="80" />
        <el-table-column prop="typeText" label="学生类型" width="100" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="statusText" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="(row.status === 0 || row.status === '0') ? 'success' : 'danger'">
              {{ row.statusText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="default" type="primary" @click="editStudent(row)">编辑</el-button>
              <el-button size="default" type="danger" @click="deleteStudent(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalStudents"
          layout="total, sizes, prev, pager, next, jumper"
          size="large"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑学生对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="showAddModal ? '新增学生' : '编辑学生'"
      width="600px"
      :before-close="closeModal"
    >
      <el-form
        ref="formRef"
        :model="studentForm"
        :rules="formRules"
        label-width="100px"
        size="large"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="studentForm.studentId" placeholder="请输入学号" size="large" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="studentForm.name" placeholder="请输入姓名" size="large" />
        </el-form-item>
         <el-form-item label="专业" prop="professionId">
           <el-select v-model="studentForm.professionId" placeholder="请选择专业" style="width: 100%" size="large">
             <el-option 
               v-for="profession in professions" 
               :key="profession.id" 
               :label="profession.name" 
               :value="profession.id" 
             />
           </el-select>
         </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input v-model="studentForm.grade" placeholder="请输入年级" size="large" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="studentForm.sex" placeholder="请选择性别" style="width: 100%" size="large">
            <el-option label="男" value="0" />
            <el-option label="女" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="学生类型" prop="type">
          <el-select v-model="studentForm.type" placeholder="请选择学生类型" style="width: 100%" size="large">
            <el-option label="本科生" value="0" />
            <el-option label="研究生" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="studentForm.phone" placeholder="请输入手机号" size="large" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="studentForm.status" placeholder="请选择状态" style="width: 100%" size="large">
            <el-option label="正常" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" @click="closeModal">取消</el-button>
          <el-button type="primary" size="large" @click="showAddModal ? addStudent() : updateStudent()">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search } from '@element-plus/icons-vue'
import { queryStudentAPI, deleteStudentAPI, addStudentAPI, updateStudentAPI } from '@/apis/studentAPI'
import { queryProfessionAPI } from '@/apis/professionAPI'

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const selectedProfession = ref('')
const selectedStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalStudents = ref(0)
const students = ref([])

// 专业列表和映射
const professions = ref([])
const professionMap = ref({})

// 获取专业数据
const fetchProfessions = async () => {
  try {
    const response = await queryProfessionAPI()
    if (response.code === 0) {
      professions.value = response.data || []
      // 构建专业映射
      professionMap.value = {}
      professions.value.forEach(profession => {
        professionMap.value[profession.id] = profession.name
      })
    } else {
      ElMessage.error(response.msg || '获取专业数据失败')
    }
  } catch (error) {
    console.error('获取专业数据失败:', error)
    ElMessage.error('获取专业数据失败')
  }
}

// 对话框相关
const dialogVisible = ref(false)
const showAddModal = ref(false)
const showEditModal = ref(false)
const editingStudent = ref(null)
const formRef = ref()

// 学生表单数据
const studentForm = ref({
  studentId: '',
  name: '',
  professionId: '',
  grade: '',
  sex: '',
  type: '',
  phone: '',
  status: ''
})

// 表单验证规则
const formRules = {
  studentId: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { pattern: /^\d{7}$/, message: '学号必须为7位数字', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur' }
  ],
  professionId: [
    { required: true, message: '请选择专业', trigger: 'change' }
  ],
  grade: [
    { required: true, message: '请输入年级', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择学生类型', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取学生数据
const fetchStudents = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      name: searchQuery.value || undefined,
      professionId: selectedProfession.value || undefined,
      status: selectedStatus.value !== '' ? selectedStatus.value : undefined
    }
    
    console.log('API请求参数:', params)
    const response = await queryStudentAPI(params)
    console.log('API响应:', response)
    if (response.code === 0) {
      const data = response.data || {}
      const records = data.records || []
      students.value = records
      if (typeof data.total === 'number') {
        totalStudents.value = data.total
      } else {
        // total 缺失时的兼容方案：最后一页 total=已查到条数，其余页构造“有下一页”的 total
        if (records.length < pageSize.value) {
          totalStudents.value = (currentPage.value - 1) * pageSize.value + records.length
        } else {
          totalStudents.value = currentPage.value * pageSize.value + 1
        }
      }
    } else {
      ElMessage.error(response.msg || '获取学生数据失败')
    }
  } catch (error) {
    console.error('获取学生数据失败:', error)
    ElMessage.error('获取学生数据失败')
  } finally {
    loading.value = false
  }
}

// 计算属性 - 过滤后的学生数据
const filteredStudents = computed(() => {
  return students.value.map(student => ({
    ...student,
    profession: professionMap.value[student.professionId] || '未知专业',
    sexText: student.sex === 0 || student.sex === '0' ? '男' : '女',
    typeText: student.type === 0 || student.type === '0' ? '本科生' : '研究生',
    statusText: student.status === 0 || student.status === '0' ? '正常' : '禁用'
  }))
})

// 方法
const exportData = () => {
  ElMessage.success('导出功能开发中...')
}

const editStudent = (student) => {
  editingStudent.value = student
  showAddModal.value = false
  showEditModal.value = true
  dialogVisible.value = true
  // 只传递必要的字段，避免传递过多参数
  // 确保数字类型转换为字符串，以便下拉框正确显示
  studentForm.value = {
    id: student.id,
    name: student.name,
    studentId: student.studentId,
    phone: student.phone,
    sex: String(student.sex),
    professionId: String(student.professionId),
    type: String(student.type),
    status: String(student.status),
    grade: String(student.grade)
  }
}

// 删除学生
const deleteStudent = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个学生吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    loading.value = true
    const response = await deleteStudentAPI(id)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      await fetchStudents()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 新增学生
const addStudent = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    // 只传递必要的字段到API，排除id字段
    // 将字符串转换回数字类型发送给API
    const addData = {
      name: studentForm.value.name,
      studentId: studentForm.value.studentId,
      phone: studentForm.value.phone,
      sex: Number(studentForm.value.sex),
      professionId: Number(studentForm.value.professionId),
      type: Number(studentForm.value.type),
      status: Number(studentForm.value.status),
      grade: Number(studentForm.value.grade)
    }
    
    console.log('新增学生数据:', addData)
    const response = await addStudentAPI(addData)
    if (response.code === 0) {
      ElMessage.success('新增学生成功')
      closeModal()
      await fetchStudents()
    } else {
      ElMessage.error(response.msg || '新增学生失败')
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error('表单验证失败')
    } else {
      console.error('新增学生失败:', error)
      ElMessage.error('新增学生失败')
    }
  } finally {
    loading.value = false
  }
}

// 编辑学生
const updateStudent = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    // 只传递必要的字段到API
    // 将字符串转换回数字类型发送给API
    const updateData = {
      id: studentForm.value.id,
      name: studentForm.value.name,
      studentId: studentForm.value.studentId,
      phone: studentForm.value.phone,
      sex: Number(studentForm.value.sex),
      professionId: Number(studentForm.value.professionId),
      type: Number(studentForm.value.type),
      status: Number(studentForm.value.status),
      grade: Number(studentForm.value.grade)
    }
    
    console.log('更新学生数据:', updateData)
    const response = await updateStudentAPI(updateData)
    if (response.code === 0) {
      ElMessage.success('编辑学生成功')
      closeModal()
      await fetchStudents()
    } else {
      ElMessage.error(response.msg || '编辑学生失败')
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error('表单验证失败')
    } else {
      console.error('编辑学生失败:', error)
      ElMessage.error('编辑学生失败')
    }
  } finally {
    loading.value = false
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  dialogVisible.value = false
  editingStudent.value = null
  studentForm.value = {
    studentId: '',
    name: '',
    professionId: '',
    grade: '',
    sex: '',
    type: '',
    phone: '',
    status: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchStudents()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchStudents()
}

// 搜索功能
const handleSearch = () => {
  console.log('搜索参数:', {
    searchQuery: searchQuery.value,
    selectedProfession: selectedProfession.value,
    selectedStatus: selectedStatus.value
  })
  currentPage.value = 1
  fetchStudents()
}

onMounted(() => {
  fetchProfessions()
  fetchStudents()
})
</script>

<style scoped>
.page-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 20px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.page-subtitle {
  font-size: 16px;
  color: #6b7280;
  margin-top: 6px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-box {
  flex: 1;
  max-width: 350px;
}

.filter-section {
  display: flex;
  gap: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 增大表格字体和间距 */
:deep(.el-table) {
  font-size: 16px;
}

:deep(.el-table th) {
  font-size: 16px;
  font-weight: 600;
  padding: 16px 0;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-table .cell) {
  font-size: 16px;
  line-height: 1.6;
}

/* 增大标签字体 */
:deep(.el-tag) {
  font-size: 14px;
  padding: 8px 12px;
}

/* 增大按钮字体 */
:deep(.el-button) {
  font-size: 14px;
  padding: 10px 16px;
}
</style>

